package com.example.smartmedicalsystem.controller;

import com.example.smartmedicalsystem.entity.*;
import com.example.smartmedicalsystem.repository.*;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/doctor")
@RequiredArgsConstructor
public class DoctorController {

    private final AppointmentRepository appointmentRepository;
    private final MedicineRepository medicineRepository;
    private final MedicalRecordRepository medicalRecordRepository;
    private final DoctorRepository doctorRepository;
    private final MessageRepository messageRepository;
    @PutMapping("/appointments/{appointmentId}/complete")
    @Transactional
    public ResponseEntity<?> completeAppointment(
            @PathVariable Long appointmentId,
            @RequestParam String diagnosis,
            @RequestParam String prescription,
            @RequestBody Map<Long, Integer> medicineQuantities) {

        try {
            Appointment appointment = appointmentRepository.findById(appointmentId)
                    .orElseThrow(() -> new RuntimeException("预约不存在"));

            // 验证预约状态
            if (appointment.getStatus() != Appointment.Status.PENDING) {
                return ResponseEntity.badRequest().body("该预约已处理");
            }

            // 处理药品库存并收集药品信息
            List<Medicine> medicines = new ArrayList<>();
            medicineQuantities.forEach((medicineId, quantity) -> {
                Medicine medicine = medicineRepository.findById(medicineId)
                        .orElseThrow(() -> new RuntimeException("药品不存在: " + medicineId));

                if (medicine.getStock() < quantity) {
                    throw new RuntimeException(medicine.getName() + "库存不足");
                }

                // 更新库存
                medicine.setStock(medicine.getStock() - quantity);
                medicineRepository.save(medicine);
                medicines.add(medicine);
            });

            // 创建病历记录
            MedicalRecord record = new MedicalRecord();
            record.setDiagnosis(diagnosis);
            record.setPrescription(prescription);
            record.setAppointment(appointment);
            record.setMedicines(medicines); // 需要实体类支持
            record.setMedicineQuantities(medicineQuantities); // 需要实体类支持

            // 更新预约状态和病历
            appointment.setStatus(Appointment.Status.COMPLETED);
            appointment.setMedicalRecord(medicalRecordRepository.save(record));
            appointmentRepository.save(appointment);
            Message msg = new Message();
            msg.setContent("诊断已完成！访问链接查看详情：/medical_record.html?appointmentId=" + appointmentId);
            msg.setReceiver(appointment.getPatient());
            messageRepository.save(msg);
            return ResponseEntity.ok(record);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }

    }

    @GetMapping("/appointments")
    public ResponseEntity<List<Appointment>> getMyAppointments(Authentication authentication) {
        // 获取当前登录医生的信息
        String username = authentication.getName();
        Doctor doctor = doctorRepository.findByUser_Username(username)
                .orElseThrow(() -> new RuntimeException("医生未找到"));
        // 查询该医生的待处理预约
        List<Appointment> appointments = appointmentRepository.findByDoctorAndStatus(doctor, Appointment.Status.PENDING);
        return ResponseEntity.ok(appointments);
    }
    @GetMapping("/medicines")
    public List<Medicine> getAvailableMedicines() {
        return medicineRepository.findByStockGreaterThan(0);
    }
}